/**
 * 登录日志拦截器
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LogService } from '../../modules/log/log.service';
import { LogType, LogLevel } from '../../interfaces/log.interface';

@Injectable()
export class LoginLogInterceptor implements NestInterceptor {
  constructor(private readonly logService: LogService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const startTime = Date.now();
    const request = context.switchToHttp().getRequest();

    return next.handle().pipe(
      tap({
        next: (data) => {
          // 记录成功的登录日志
          this.logService.create(
            LogType.LOGIN,
            LogLevel.INFO,
            request,
            Date.now() - startTime,
            JSON.stringify(data),
          ).catch(err => {
            console.error('Failed to save login log:', err);
          });
        },
        error: (error) => {
          // 记录失败的登录日志
          this.logService.create(
            LogType.LOGIN,
            LogLevel.ERROR,
            request,
            Date.now() - startTime,
            undefined,
            error.message,
          ).catch(err => {
            console.error('Failed to save login log:', err);
          });
        },
      }),
    );
  }
} 